package com.health.controller.report;

import com.alibaba.dubbo.config.annotation.Reference;
import com.health.constant.MessageConstant;
import com.health.entity.FileResult;
import com.health.entity.PageResult;
import com.health.entity.QueryPageBean;
import com.health.entity.Result;
import com.health.pojo.Report;
import com.health.service.MemberService;
import com.health.service.ReportService;
import com.health.service.SetmealService;
import com.health.utils.DateUtils;
import com.health.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Classname ReportController
 * @Description TODO
 * @Version 1.0.0
 * @Date 2023/3/17 14:47
 * @Author RainGrd
 */
//@RestController
@RestController
@Slf4j
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;


    /**
     * 会员数量统计
     *
     * @return
     */
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    @RequestMapping("/getMemberReport.do")
    //@ResponseBody
    public Result getMemberReport() {
        try {
            //动态获取过去1年的12个月，并封装到集合中
            List<String> months = new ArrayList<>();
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -12);//add方法用于计算
            for (int i = 0; i < 12; i++) {
                calendar.add(Calendar.MONTH, 1);//add方法用于计算
                months.add(DateUtils.parseDate2String(calendar.getTime(), "yyyy.MM"));
            }
            //根据月份查询对应的会员数量
            List<Integer> memberCount = memberService.findMemberCountByMonth(months);

            Map<String, Object> data = new HashMap<>();
            data.put("months", months);
            data.put("memberCount", memberCount);
            return Result.success(data, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error();
        }

    }

    /**
     * 套餐占比统计
     *
     * @return
     */
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    @RequestMapping("/getSetmealReport.do")
    //@ResponseBody
    public Result getSetmealReport() {
        List<Map<String, Object>> list = setmealService.findSetmealCount();

        Map<String, Object> map = new HashMap<>();
        map.put("setmealCount", list);

        List<String> setmealNames = new ArrayList<>();
        for (Map<String, Object> m : list) {
            String name = (String) m.get("name");
            setmealNames.add(name);
        }
        map.put("setmealNames", setmealNames);

        return Result.success(map, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS);
    }

    /**
     * 获取运营统计数据
     *
     * @return
     */
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    @RequestMapping("/getBusinessReportData.do")
    //@ResponseBody
    public Result getBusinessReportData() {
        try {
            Map<String, Object> result = reportService.getBusinessReport();
            return Result.success(result, MessageConstant.GET_BUSINESS_REPORT_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error(MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 导出Excel报表
     *
     * @return
     */
    @RequestMapping("/exportBusinessReport.do")
    //@ResponseBody
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            //远程调用报表服务获取报表数据
            Map<String, Object> result = reportService.getBusinessReport();

            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            ClassPathResource classPathResource = new ClassPathResource("/template/report_template.xlsx");
            InputStream inputStream = classPathResource.getInputStream();
            String path = this.getClass().getClassLoader().getResource("template/report_template.xlsx").getPath();
            System.out.println(path);
            //获得Excel模板文件绝对路径
            /*String templateRealPath = request.getSession().getServletContext().getRealPath("/static/template") +
                    File.separator + "report_template.xlsx";*/

            //读取模板文件创建Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(path)));
            XSSFSheet sheet = workbook.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for (Map map : hotSetmeal) {//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error(MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //文件上传，实现预约设置数据批量导入
    @RequestMapping("/upload.do")
    //@ResponseBody
    public Result upload(@RequestParam("reportFile") MultipartFile reportFile) {
        System.out.println(reportFile);

        //设置文件名
//        String originalFilename = reportFile.getOriginalFilename();//原始文件名（上传时文件的名字） 3bd90d2c-4e82-42a1-a401-882c88b06a1a2.jpg
//        int index = originalFilename.lastIndexOf(".");//获取最后一个点的位置
//        String extention = originalFilename.substring(index);//通过截取字符串获取：.jpg
//        String fileName = UUID.randomUUID().toString() + extention;//	FuM1Sa5TtL_ekLsdkYWcf5pyjKGu.jpg
        try {
            //将文件上传到七牛云服务器
//            QiniuUtils.upload2Qiniu(reportFile.getBytes(),fileName);//fileName使用uuid自动产生，使其不重复
            FileResult fileResult = FileUtils.uploadFile(reportFile, "", "");
            log.info("fileResult:{}", fileResult);
//            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);//操作set集合，想指定的set集合里面添加数据
            //往t_report表里面添加数据，证明当前报告已经上传了
            return Result.success(fileResult.getFileName(), MessageConstant.UPLOAD_SUCCESS);
        } catch (IOException e) {
            log.error(e.getMessage());
            return Result.error();
        }
    }

    //进行报告的保存或者是更新
    @RequestMapping(value = "/update.do")
    //@ResponseBody
    public Result update(@RequestBody Report report) {
        try {
            log.info("更新时的：" + report.getFileName());
            log.info("更新时的体检报告：" + report);
            log.info("更新时的：" + report.getMemberId());
            int i = reportService.updateReport(report);
            return i > 0 ? Result.success() : Result.error();
        } catch (Exception e) {
            //证明调用失败
            log.error(e.getMessage());
            return Result.error();
        }

    }

    @RequestMapping("/findReportByPhoneNumber.do")
    //@ResponseBody
    public Result findReportByPhoneNumber(String phoneNumber) {
        return reportService.queryReportByPhoneNumber(phoneNumber);
    }


    //删除该报告内容
    @RequestMapping("/delete.do")//使其那个被访问到
    //@ResponseBody
    public Result delete(Integer id) {
        try {
            int i = reportService.deleteById(id);
            return i > 0 ? Result.success() : Result.error();
        } catch (Exception e) {
            //证明调用失败
            log.error(e.getMessage());
            return Result.error();
        }
    }


    @RequestMapping("/queryReportForPage.do")
    //@ResponseBody
    public PageResult queryReportForPage(@RequestBody QueryPageBean queryPageBean) {
       /* org.springframework.security.core.userdetails.User user =
                (org.springframework.security.core.userdetails.User)
                        SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        log.info("正在登录的用户:{}", user);*/
        return reportService.queryReportListAll(queryPageBean);
    }

    /**
     * 下载体检报告
     *
     * @param fileName
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/download.do")
    //@ResponseBody
    public String download(@RequestParam("fileName") String fileName, @RequestParam("id") Integer id, HttpServletResponse response) throws IOException {
        FileUtils.downloadFile(fileName, response);
        //查询体检报告对象
        Report report = reportService.queryReportById(id);
        //修改体检报告状态
        report.setReportStatus(Report.REPORT_STATUS_DOWNLOAD_YES);
        reportService.updateReport(report);
        return null;
    }


}
